package com.itlong.cloud.controller.expenses;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.property.PropertyFeeRuleDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyLadderFeeDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyRuleGetDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyRuleDetailVO;
import com.itlong.cloud.POJO.VO.property.PropertyRuleVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.project.property.IPropertyRuleServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <desc>
 *      物业系统收费管理收费规则聚合Controller。
 * </desc>
 * @createDate 2018/08/09
 */
@RestController
@RequestMapping(path = "/expenses/rule")
public class PropertyRuleController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(PropertyRuleController.class);

    @Autowired
    IPropertyRuleServiceClient iPropertyRuleServiceClient;


    /**
     * <desc>
     *      分页查询收费规则
     * <desc/>
     *
     * @param propertyRuleGetDTO 查询收费规则数据
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @ResponseBody
    @AuthAccessRequired
    @RequestMapping(path = "/getRuleByPage", method = RequestMethod.POST)
    public Object getRuleByPage(PropertyRuleGetDTO propertyRuleGetDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyRuleGetDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyRuleGetDTO.class, request);
            if(StringUtils.isBlank(propertyRuleGetDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }

            Page<PropertyRuleVO> result =
                    iPropertyRuleServiceClient.getRuleByPage(propertyRuleGetDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_收费管理_查询收费规则信息】查询收费规则信息失败"), e);
        }
    }

    /**
     * <desc>
     *      根据收费类型查询收费规则
     * <desc/>
     *
     * @param projectId 项目编号
     * @param feeType 收费类型：1抄表费 2物业费 3维修费 4停车费
     * @param feeCycle 收费周期：1月 2季度 3年
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/15
     */
    @RequestMapping(path = "/getRuleByFeeType", method = RequestMethod.POST)
    @ResponseBody
    public Object getRuleByFeeType(String projectId, String feeType, String feeCycle) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            feeType = request.getAttribute("feeType") == null ? null : request.getAttribute("feeType").toString();
            feeCycle = request.getAttribute("feeCycle") == null ? "" : request.getAttribute("feeCycle").toString();
            if(StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(feeType)) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEE_TYPE_EMPTY_ERR.getErrorCode());
            }
            List<PropertyRuleVO> result =
                    iPropertyRuleServiceClient.getRuleByFeeType(projectId,feeType,feeCycle);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_收费管理_查询收费规则信息】查询收费规则信息失败"), e);
        }
    }

    /**
     * <desc>
     *      查看收费规则
     * <desc/>
     *
     * @param feeRuleId 收费规则ID
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @ResponseBody
    @AuthAccessRequired
    @RequestMapping(path = "/getRuleDetail", method = RequestMethod.POST)
    public Object getRuleDetail(String feeRuleId, String projectId) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            feeRuleId = request.getAttribute("feeRuleId") == null ? null : request.getAttribute("feeRuleId").toString();
            if(StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(feeRuleId)) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEERULEID_EMPTY_ERR.getErrorCode());
            }

            PropertyRuleDetailVO result =
                    iPropertyRuleServiceClient.getRuleDetail(feeRuleId,projectId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_收费管理_查看收费规则信息】查看收费规则信息失败"), e);
        }
    }

    /**
     * <desc>
     *      新增收费规则
     * <desc/>
     *
     * @param propertyFeeRuleDTO 收费规则保存信息
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @RequestMapping(path = "/saveRule", method = RequestMethod.POST)
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.RULE_INSERT_LOG_DESC)
    @ResponseBody
    public Object saveRule(PropertyFeeRuleDTO propertyFeeRuleDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyFeeRuleDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyFeeRuleDTO.class, request);
            if(StringUtils.isBlank(propertyFeeRuleDTO.getProjectId())) {//项目编号
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getRuleName())) {//规则名称
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_RULE_NAME_EMPTY_ERR.getErrorCode());
            }
            if(iPropertyRuleServiceClient.checkRuleNameRepeat(propertyFeeRuleDTO.getRuleName(),propertyFeeRuleDTO.getProjectId(), null) > 0) {//规则名称重复判断
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_RULE_NAME_REPEAT_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getFeeType())) {//收费类型
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEE_TYPE_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getCalculateType())) {//计算方式
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_CALCULATE_TYPE_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getFeeCycle())) {//收费周期
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEE_CYCLE_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getFeeDay())) {//收费日
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEE_DAY_EMPTY_ERR.getErrorCode());
            }
            if ("2".equals(propertyFeeRuleDTO.getCalculateType())) {//计算方式为固定金额
                if (StringUtils.isBlank(propertyFeeRuleDTO.getFixedPrice())) {//固定金额不能为空
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_FIXED_PRICE_EMPTY_ERR.getErrorCode());
                }
            }
            if ("1".equals(propertyFeeRuleDTO.getCalculateType())) {//计算方式为单价*数量
                if (StringUtils.isBlank(propertyFeeRuleDTO.getMeasureType())) {//计量方式不能为空
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_MEASURE_TYPE_EMPTY_ERR.getErrorCode());
                }
                if ("1".equals(propertyFeeRuleDTO.getMeasureType())) {//计量方式为按单价
                    if (StringUtils.isBlank(propertyFeeRuleDTO.getPrice())) {//单价不能为空
                        return new MessageVO(PropertyErrorCodeEnum.PROJECT_PRICE_TYPE_EMPTY_ERR.getErrorCode());
                    }
                }
                if ("2".equals(propertyFeeRuleDTO.getMeasureType())) {//计量方式为阶梯收费
                    if (StringUtils.isBlank(propertyFeeRuleDTO.getLadderFeeListJson())){
                        return new MessageVO(PropertyErrorCodeEnum.PROJECT_LADDER_FEE_EMPTY_ERR.getErrorCode());
                    }
                }
            }
            if (StringUtils.isNotBlank(propertyFeeRuleDTO.getLadderFeeListJson())){
                List<PropertyLadderFeeDTO> list = JSON.parseArray(propertyFeeRuleDTO.getLadderFeeListJson(),
                        PropertyLadderFeeDTO.class);
                propertyFeeRuleDTO.setLadderFeeList(list);
            }
            iPropertyRuleServiceClient.saveRule(propertyFeeRuleDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), true);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_收费管理_新增收费规则】新增收费规则失败"), e);
        }
    }

    /**
     * <desc>
     *      更新收费规则
     * <desc/>
     *
     * @param propertyFeeRuleDTO 收费规则保存信息
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @RequestMapping(path = "/updateRule", method = RequestMethod.POST)
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.RULE_UPDATE_LOG_DESC)
    @ResponseBody
    public Object updateRule(PropertyFeeRuleDTO propertyFeeRuleDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyFeeRuleDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyFeeRuleDTO.class, request);
            if(StringUtils.isBlank(propertyFeeRuleDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getFeeRuleId())) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEERULEID_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getRuleName())) {//规则名称
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_RULE_NAME_EMPTY_ERR.getErrorCode());
            }
            if(iPropertyRuleServiceClient.checkRuleNameRepeat(propertyFeeRuleDTO.getRuleName(),propertyFeeRuleDTO.getProjectId(),propertyFeeRuleDTO.getFeeRuleId()) > 0) {//规则名称重复判断
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_RULE_NAME_REPEAT_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getFeeType())) {//收费类型
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEE_TYPE_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getCalculateType())) {//计算方式
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_CALCULATE_TYPE_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getFeeCycle())) {//收费周期
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEE_CYCLE_EMPTY_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(propertyFeeRuleDTO.getFeeDay())) {//收费日
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEE_DAY_EMPTY_ERR.getErrorCode());
            }
            if ("2".equals(propertyFeeRuleDTO.getCalculateType())) {//计算方式为固定金额
                if (StringUtils.isBlank(propertyFeeRuleDTO.getFixedPrice())) {//固定金额不能为空
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_FIXED_PRICE_EMPTY_ERR.getErrorCode());
                }
            }
            if ("1".equals(propertyFeeRuleDTO.getCalculateType())) {//计算方式为单价*数量
                if (StringUtils.isBlank(propertyFeeRuleDTO.getMeasureType())) {//计量方式不能为空
                    return new MessageVO(PropertyErrorCodeEnum.PROJECT_MEASURE_TYPE_EMPTY_ERR.getErrorCode());
                }
                if ("1".equals(propertyFeeRuleDTO.getMeasureType())) {//计量方式为按单价
                    if (StringUtils.isBlank(propertyFeeRuleDTO.getPrice())) {//单价不能为空
                        return new MessageVO(PropertyErrorCodeEnum.PROJECT_PRICE_TYPE_EMPTY_ERR.getErrorCode());
                    }
                }
                if ("2".equals(propertyFeeRuleDTO.getMeasureType())) {//计量方式为阶梯收费
                    if (StringUtils.isBlank(propertyFeeRuleDTO.getLadderFeeListJson())){
                        return new MessageVO(PropertyErrorCodeEnum.PROJECT_LADDER_FEE_EMPTY_ERR.getErrorCode());
                    }
                }
            }
            if (StringUtils.isNotBlank(propertyFeeRuleDTO.getLadderFeeListJson())){
                List<PropertyLadderFeeDTO> list = JSON.parseArray(propertyFeeRuleDTO.getLadderFeeListJson(),
                        PropertyLadderFeeDTO.class);
                propertyFeeRuleDTO.setLadderFeeList(list);
            }
            iPropertyRuleServiceClient.updateRule(propertyFeeRuleDTO);
            return new MessageVO(propertyFeeRuleDTO.getFeeRuleId(), BaseErrorCodeEnum.SUCCESS.getErrorCode(), true);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_收费管理_更新收费规则】更新收费规则失败"), e);
        }
    }

    /**
     * <desc>
     *      删除收费规则
     * <desc/>
     *
     * @param feeRuleId 收费规则ID
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @RequestMapping(path = "/deleteRule", method = RequestMethod.POST)
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.RULE_DELETE_LOG_DESC)
    @ResponseBody
    public Object deleteRule(String feeRuleId) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            feeRuleId = request.getAttribute("feeRuleId") == null ? null : request.getAttribute("feeRuleId").toString();
            if(StringUtils.isBlank(feeRuleId)) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_FEERULEID_EMPTY_ERR.getErrorCode());
            }
            if (iPropertyRuleServiceClient.deleteRuleCheck(feeRuleId) > 0) {
                return new MessageVO(PropertyErrorCodeEnum.RULE_IS_BINDING.getErrorCode());
            }
            iPropertyRuleServiceClient.deleteRule(feeRuleId);
            return new MessageVO(feeRuleId, BaseErrorCodeEnum.SUCCESS.getErrorCode(), true);
        } catch (Exception e) {
            throw new DataAccessException(String.format(
                    "【物业系统_收费管理_删除收费规则】删除收费规则失败"), e);
        }
    }

}